/*
 * Copyright (c) 2015 qunar. All Rights Reserved.
 */
package com.guoyu.project.service;

import java.io.File;
import java.io.IOException;

import com.guoyu.project.common.utils.PropertyUtil;
import org.apache.commons.codec.digest.DigestUtils;
import org.apache.commons.io.FileUtils;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;


/**
 * @author: libo Date: 15-6-6 Time: 下午11:56
 */
@Service
public class FileUploadService {

    private final static Logger logger = LoggerFactory.getLogger(FileUploadService.class);

    private final static String DOT = ".";
    private final static String UPLOADER = "uploader";
    private final static String UPLOADER_PATH = PropertyUtil.getProperty("uploader.path");
    static {
        try {
            FileUtils.forceMkdir(new File(UPLOADER_PATH));
        } catch (IOException e) {
            throw new ExceptionInInitializerError(e);
        }
    }

    public String upload(MultipartFile uploadFile) {
        if (null == uploadFile) {
            return StringUtils.EMPTY;
        }
        String fileName = uploadFile.getOriginalFilename();
        if (StringUtils.isBlank(fileName)) {
            return StringUtils.EMPTY;
        }
        // 存放文件的相对路劲（文件扩展名+md5(文件名)）
        String relativeFilePath = generateFilePath(fileName);
        try {
            // 文件路径，配置的文件路劲+文件扩展名+md5(文件名)
            String filePath = UPLOADER_PATH + relativeFilePath;

            File saveFile = new File(filePath);
            if (!saveFile.exists()) {
                FileUtils.forceMkdir(saveFile);
                uploadFile.transferTo(saveFile);
            }

            return relativeFilePath;
        } catch (IOException e) {
            logger.error("上传文件保存失败,fileName:{}", fileName, e);
            return StringUtils.EMPTY;
        }

    }

    private static String generateFilePath(String fileName) {
        String extension = getExtension(fileName);
        return File.separator + UPLOADER + File.separator + extension + File.separator + DigestUtils.md5Hex(fileName)
                + DOT + extension;
    }

    public static String getExtension(String fileName) {
        if (StringUtils.INDEX_NOT_FOUND == StringUtils.indexOf(fileName, DOT)) {
            return StringUtils.EMPTY;
        }
        return StringUtils.substringAfterLast(fileName, DOT);
    }

}
